﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Windows.Forms;
using LocationAddress.Models;
using Newtonsoft.Json;
using System.Linq;

namespace LocationAddress {
    public partial class MainFrm : Form {
        private readonly string ak = "XBPX8dmIuAzluWeOtTAzsCECpkxkLudV";
        private readonly string baiduAddress = "http://api.map.baidu.com/geocoder/v2/";

        public MainFrm() {
            InitializeComponent();
            this.textBoxLocation.KeyUp += TextBoxLocation_KeyUp;
        }

        private void TextBoxLocation_KeyUp(object sender, KeyEventArgs e) {
            if(e.Control && e.KeyCode == Keys.A) {
                ((TextBox)sender).SelectAll();
            }
        }

        public Root GetSupplierLocation(string address) {
            var akInternal = string.IsNullOrEmpty(this.textBoxAK.Text) ? ak : this.textBoxAK.Text;
            var parameters = string.Format("address={0}&output=json&ak={1}", address, akInternal);
            try {
                var uri = $"{baiduAddress}?{parameters}";
                var webRequest = WebRequest.Create(uri);
                webRequest.Method = "GET";
                HttpWebResponse httpWebResponse = webRequest.GetResponse() as HttpWebResponse;
                if(httpWebResponse == null) return null;
                using(WebResponse response = webRequest.GetResponse()) {
                    using(var streamReader = new StreamReader(response.GetResponseStream())) {
                        var root = streamReader.ReadToEnd();
                        return JsonConvert.DeserializeObject<Root>(root);
                    }
                }
            } catch(Exception) {
                return new Root {
                    Status = 500
                };
            }
        }

        private void btnGetLocation_Click(object sender, EventArgs e) {
            this.textBoxLocation.Text = string.Empty;

            if(string.IsNullOrEmpty(this.textBoxAddress.Text)) {
                MessageBox.Show(this, "请录入需要获取经纬度的地址", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            var listAddress = new List<string>();
            listAddress.AddRange(this.textBoxAddress.Text.Split(','));
            var lineNumber = 1;
            foreach(var address in listAddress.Where(address => !string.IsNullOrEmpty(address)).Distinct().ToArray()) {
                try {
                    var root = GetSupplierLocation(address);
                    if(root == null) {
                        this.textBoxLocation.Text += string.Format("{0}  地址：{1}，经度：{2}，纬度：{3}，获取结果：失败;" + Environment.NewLine, lineNumber, address, 0, 0);
                        continue;
                    }
                    switch(root.Status) {
                        case default(int):
                            this.textBoxLocation.Text += string.Format("{0}  地址：{1}，经度：{2}，纬度：{3}，获取结果：{4}" + Environment.NewLine, lineNumber, address, root.Result.Location.Lng, root.Result.Location.Lat, root.Status == 0 ? "成功" : "失败");
                            break;
                        case 1:
                            this.textBoxLocation.Text += string.Format("{0}  地址：{1}，经度：{2}，纬度：{3}，获取结果：{4}" + Environment.NewLine, lineNumber, address, default(int), default(int), root.Msg);
                            break;
                        default:
                            if(root.Result == null) {
                                this.textBoxLocation.Text += string.Format("{0}  地址：{1}，经度：{2}，纬度：{3}，获取结果：{4}" + Environment.NewLine, lineNumber, address, default(int), default(int), root.Message);
                            } else {
                                if(root.Result.Location == null)
                                    this.textBoxLocation.Text += string.Format("{0}  地址：{1}，经度：{2}，纬度：{3}，获取结果：{4}" + Environment.NewLine, lineNumber, address, default(int), default(int), root.Status == 0 ? "成功" : "失败");
                                if(root.Result.Location != null)
                                    this.textBoxLocation.Text += string.Format("{0}  地址：{1}，经度：{2}，纬度：{3}，获取结果：{4}" + Environment.NewLine, lineNumber, address, root.Result.Location.Lng, root.Result.Location.Lat, root.Status == 0 ? "成功" : "失败");
                            }
                            break;
                    }

                } catch(Exception ex) {
                    this.textBoxLocation.Text += string.Format("{0}  地址：{1}，经度：{2}，纬度：{3}，获取结果：{4};" + Environment.NewLine, lineNumber, address, 0, 0, ex.Message);
                    continue;
                }
                lineNumber++;
            }
        }
    }
}
